import requests
import json
import time
import winsound
import os
import socket
class Qianka(object):
    domain='https://qianka.com'
    check_task_state_url='/s4/lite.subtask.checkState'

    task_list_url='/s4/lite.subtask.list'
    start_task_url='/s4/lite.subtask.start'
    zstask_list_url='/s4/lite.zstask.list'
    zstask_start_url='/s4/lite.zstask.start'
    zstask_detail_url='/s4/lite.zstask.detail'
    zstask_checkstate_url='/s4/lite.zstask.checkState'
    zstask_open_url='/s5k/subtask.open'
    zstask_open_status_url='/s4/lite.open.status'
    proxy={
        'http':'http://127.0.0.1:1080/pac?t=20181129194333654&secret=o44v7lVUpYdZ/dpkPbs0WuPERND/8PBTJgqol1L3WkE=',
        'http':'http://35.209.121.1:9528',
        'http':'http://104.16.5.188'
    }
    appheaders={
        'Host': 'qianka.com',
        'Accept': 'application/json, text/plain, */*',
        'Connection': 'keep-alive',
        'Cookie': 'DIS4=7d392b24a0d14182b932b44bb8d2502c;qk_guid_appstore=9215b95d-fcdf-47ea-acb8-7c9facc22bf3; lite_token=d0410c18d72cfef761a7e8c45cb290de;_uab_collina=154078641823660930419766; ln=1; lu=59847332; mu=0;user_first_vist_rongyuka=1',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 version = 1.1.2018101101 bid=ka.life.app',
        'Accept-Language': 'zh-cn',
        'Accept-Encoding': 'gzip, deflate',
    }
    appheaders1={
        'Host': 'qianka.com',
        'Accept': 'application/x-www-form-urlencoded, text/plain, */*',
        'Connection': 'keep-alive',
        'Cookie': 'DIS4=7d392b24a0d14182b932b44bb8d2502c;qk_guid_appstore=9215b95d-fcdf-47ea-acb8-7c9facc22bf3; lite_token=d0410c18d72cfef761a7e8c45cb290de;_uab_collina=154078641823660930419766; ln=1; lu=59847332; mu=0;user_first_vist_rongyuka=1',
        'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 version = 1.1.2018101101 bid=ka.life.app',
        'Accept-Language': 'zh-cn',
        'Accept-Encoding': 'gzip, deflate',
    }
    # appheaders = {
    #     'Host': 'qianka.com',
    #     'Accept': 'application/json, text/plain, */*',
    #     'Connection': 'keep-alive',
    #     'Cookie': 'DIS4=caa40e2c0613404aa92fe074a357e1b5; ln=1; lu=59865469; lite_token=d0410c18d72cfef761a7e8c45cb290de; qk_guid_appstore=9215b95d-fcdf-47ea-acb8-7c9facc22bf3; _uab_collina=154078641823660930419766; user_first_vist_rongyuka=1',
    #     'User-Agent': 'Mozilla/5.0 (iPhone; CPU iPhone OS 10_3_3 like Mac OS X) AppleWebKit/603.3.8 (KHTML, like Gecko) Mobile/14G60 version = 1.1.2018101101 bid=ka.life.app',
    #     'Accept-Language': 'zh-cn',
    #     'Accept-Encoding': 'gzip, deflate',
    # }
    appheaders2={
        'X-QK-DIS': '65f84049c09d43959361483f93418e0e',
        'X-QK-AUTH': '6D343451-3E09-4977-8EDC-C8553A22547A|44c3abc9-cc1e-4d51-a3e9-6d3131543826|',
        'X-QK-SCHEME': 'ka.life.app',
        'Cookie': 'DIS4=65f84049c09d43959361483f93418e0e; qk_guid_appstore=9215b95d-fcdf-47ea-acb8-7c9facc22bf3; _uab_collina = 154078641823660930419766;ln = 1;lu = 59847332;user_first_vist_rongyuka = 1',
        'User-Agent': 'WhichYouLove/2018101101 CFNetwork/811.5.4 Darwin/16.7.0',
        'Access-Control-Allow-Origin': '*',
        'X-QK-TIME': '1540970403',
        'X-QK-DSID': '1942646755',
        'X-QK-SIGN': 'F69ACCC581007E3660D4FE73A8EDFE46',
        'X-QK-EXTENSION': '10.3.3|1|121c83f7600cb2a799f',
        'X-QK-PUSH-STATE': '1',
        'Access-Control-Allow-Headers': 'X-Qk-Auth, *',
        'Content-Length': '43730',
        'Connection': 'keep-alive',
        'X-QK-TOKEN': 'd0410c18d72cfef761a7e8c45cb290de',
        'X-QK-TAG': '<72fd28e9 118e286c 731e1687 f4276343 348fde85 fec64887 cbd2516c 5c115eea>',
        'X-QK-API-KEY': 'c26007f41f472932454ea80deabd612c',
        'Accept-Language': 'zh-cn',
        'X-QK-APPV': 'iPhone9,1|1350.000000|ka.life.app|1.1.2018101101',
        'Content-Type': 'application/octet-stream',
        'Accept': '*/*',
        'Accept-Encoding': 'gzip, deflate',
        'X-QK-CDID': 'D2OyGCRmjXI4N6boopa6P7g4qvEBxhs4EpxtWzdkI6VigX55',
    }
    ignore_taskid=[239731,242644]
    def __init__(self):
        pass

    def gettasklist(self):
        """
        获取任务详情列表
        """
        r = requests.get(self.domain + self.task_list_url, headers=self.appheaders,proxies=self.proxy)
        # print(r.text)
        # print(json.dumps(r.json()))
        r_task=json.loads(r.text,encoding='utf-8')
        if r_task['err_msg']!='':
            print(r_task['err_msg'])
            return []

        tasklists=r_task['payload']['tasks']
        # print('get---',tasklists)
        return  tasklists

        pass
    def qiangtask(self):
        """
        抢任务
        """
        while True:

            print('重新刷新任务列表')
            taskslists=self.gettasklist()
            # print(taskslists,len(taskslists))
            # exit()
            if len(taskslists)==0:
                print('当前时间没有任务,等待5秒自动刷新')
                time.sleep(5)
                continue
            #  默认没有抢成功
            qiang_success=False
            for task in taskslists:
                # print(task)
                if task['id'] in self.ignore_taskid:
                    continue
                start_data={
                    'task_id':task['id'],
                    'quality':task['is_quality']
                }
                # 不抢付费应用
                # if task['tags'][0]=='付费应用':
                #                 #     continue

                tag=task['tags'][len(task['tags'])-1]
                if task['qty']==0:
                    print('任务 %s,任务id:%d,剩余:%d ' % (task['title'], task['id'],task['qty']))
                    continue
                print('正在抢任务 %s,任务id:%d %s' % (task['title'],task['id'],tag))
                qiangcount=1
                while qiangcount < 5:
                    print('正在尝试第 %d 次抢任务' % qiangcount)
                    r = requests.get(self.apiurl(self.start_task_url), params=start_data, headers=self.appheaders,proxies=self.proxy)
                    # print(r.json())
                    qiang_status=json.loads(r.text,encoding='utf-8')
                    if qiang_status['err_msg']!='':
                        print('休息5s钟，%s' % qiang_status['err_msg'])
                        time.sleep(5)
                        continue
                    if qiang_status['payload']['type']==1:
                        print('%s,等待1s' % qiang_status['payload']['message'])
                        rr = requests.get(self.apiurl(self.start_task_url), params=start_data, headers=self.appheaders,proxies=self.proxy)
                        qiang_status = json.loads(rr.text,encoding='utf-8')
                        # print('*****',qiang_status,qiang_status['payload']['message'])
                        time.sleep(2)
                        if qiang_status['payload']['type']==2:
                            qiang_success=True
                            if self.gethostname():
                                os.system("calc.exe")
                            else:
                                winsound.PlaySound("alipay", winsound.SND_FILENAME)
                            print('[%s]恭喜你抢到一个任务 %s，奖励 %s元;任务状态：%s;快去appstore下载' % (time.strftime('%Y-%m-%d %H:%M:%S'),task['title'],task['reward'],qiang_status['payload']['message']))
                            break
                        if qiang_status['payload']['type']==3:
                            print('任务结果：%s' % (qiang_status['payload']['message']))

                            # print('失败次数%d' % qiangcount)
                            time.sleep(3)
                    qiangcount += 1
                if qiang_success == True:
                    break
            if qiang_success==True:
                break
            time.sleep(5)
            # print(json.dumps(r.json()))
        pass
    def checktaskstate(self):
        """
        校验任务是否完成

        """
        statedata={'task_id':239420}

        r=requests.get(self.apiurl(self.check_task_state_url),params=statedata,headers=self.appheaders)
        print(r.json())

        pass

    def zstasklist(self):
        r=requests.get(self.apiurl(self.zstask_list_url),headers=self.appheaders)
        zs_re=r.json()
        if zs_re['err_code'] !=0:
            return False
        return zs_re['payload']['tasks']

    def zstaskstart(self):
        self.appheaders['Content-Type']='application/x-www-form-urlencoded'
        #     'Content-Type': ,
        #
        # })
        zs_start_data={
            'zs_task_id':41110
        }
        print(self.apiurl(self.zstask_start_url))
        r=requests.post(self.apiurl(self.zstask_start_url),data=zs_start_data,headers=self.appheaders)
        print(r.text)

    def zstaskdetail(self):
        zs_detail_data={
            'zs_task_id':41110
        }
        r=requests.get(self.apiurl(self.zstask_detail_url),params=zs_detail_data,headers=self.appheaders)
        print(r.json())
        pass
    def zstaskcheckstate(self):
        zs_detail_data = {
            'zs_task_id': 41110
        }
        r=requests.get(self.apiurl(self.zstask_checkstate_url),params=zs_detail_data,headers=self.appheaders)
        print(r.json())
        pass
    def zstaskopen(self):
        r=requests.post(self.apiurl(self.zstask_open_url),headers=self.appheaders2)
        print(r.status_code)
        pass

    def ztaskopenstatus(self):
        # u='https://qianka.com/s4/lite.open.status?task_id=41151&task_type=2'
        open_status={
            'task_id':41151,
            'task_type':2
        }
        r=requests.get(self.apiurl(self.zstask_open_status_url),params=open_status,headers=self.appheaders)
        print(r.text)
        pass

    def apiurl(self,url):
        if url=='':
            return False
        return self.domain+url

    def gethostname(self):
        hostName = socket.gethostname()
        return hostName=='lenovo-PC'
    def demo(self):
        r=requests.post('http://172.19.219.113:8005/index.php',headers=self.appheaders1)
        print(r.text)
        pass
if __name__=='__main__':
    qianka=Qianka()
    # qianka.gettasklist()
    qianka.qiangtask()
    # qianka.demo()
    # qianka.zstasklist()
    # qianka.zstaskstart()
    # qianka.zstaskdetail()
    # qianka.checktaskstate()
    # qianka.qiangtask()
    # qianka.ztaskopenstatus()